<template>
    <!--    角色搜索条件框-->
    <div class="cardContent">
        <a-form
                ref="formRef"
                layout="inline"
                :model="searchData">
            <a-form-item label="关键词">
                <a-input v-model:value="searchData.keyWord" placeholder="请输入关键信息"></a-input>
            </a-form-item>
            <a-form-item label="所属部门">
                <a-select
                        ref="select"
                        v-model:value="searchData.departmentId"
                        placeholder="请选择部门"
                        :options="departmentList"
                        :field-names="{label: 'name', value: 'id'}"
                ></a-select>
            </a-form-item>
            <a-form-item>
                <a-space>
                    <a-button type="primary" @click="load(1)">搜索</a-button>
                    <a-button type="default" @click="reset">重置</a-button>
                </a-space>
            </a-form-item>
        </a-form>
    </div>
    <!--    角色列表展示-->
    <div class="cardContent">
        <a-button type="primary" @click="openModal({})">新增</a-button>
        <a-table :dataSource="roleList"
                 style="margin-top: 10px"
                 :columns="columns"
                 :pagination="false"
                 size="small"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <a-space v-if="column.key == 'action'">
                    <a-button type="primary" ghost @click="openRoleUserDraw(record.id,record.isLeader)">用户</a-button>
                    <a-button type="primary" @click="openModal(record)">编辑</a-button>
                    <a-popconfirm
                            title="是否确认删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger" v-if="record.isLeader != 1">删除</a-button>
                    </a-popconfirm>
                    <a-button type="danger" ghost @click="openAuthorization(record)">授权</a-button>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
    </div>
    <a-drawer
            v-model:visible="visible"
            class="custom-class"
            width="600"
            title="新增或编辑"
            placement="right"
            :footer-style="{textAlign: 'right'}"
    >
        <a-form
                :model="role"
                name="basic"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }"
                autocomplete="off">
            <a-form-item label="角色名称" v-bind="validateInfos.name">
                <a-input v-model:value="role.name"/>
            </a-form-item>
            <a-form-item label="是否部门角色">
                <a-radio-group v-model:value="role.isDepartmentRole" button-style="solid">
                    <a-radio-button :disabled="role.isLeader == 1" :value="1">是</a-radio-button>
                    <a-radio-button :disabled="role.isLeader == 1" :value="0" @click="role.departmentId = null">否
                    </a-radio-button>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="所属部门"
                         v-bind="validateInfos.departmentId">
                <a-select
                        ref="select"
                        v-model:value="role.departmentId"
                        :disabled="role.isDepartmentRole == 0 || role.isLeader == 1"
                        placeholder="请选择部门"
                        :options="departmentList"
                        :field-names="{label: 'name', value: 'id'}"
                ></a-select>
            </a-form-item>
            <a-form-item label="基本工资" v-bind="validateInfos.baseSalary">
                <a-input-number v-model:value="role.baseSalary" addon-after="￥" min="1500"/>
            </a-form-item>
            <a-form-item label="角色描述">
                <a-textarea
                        v-model:value="role.remark"
                        :rows="4"/>
            </a-form-item>
        </a-form>
        <template #footer>
            <a-space>
                <a-button type="default" @click="visible = false">取消</a-button>
                <a-button type="primary" @click="saveOrUpdate">保存</a-button>
            </a-space>
        </template>
    </a-drawer>
    <a-drawer
            v-model:visible="roleUserVisible"
            class="custom-class"
            width="600"
            title="角色用户"
            placement="right"
    >
        <a-input-search
                v-model:value="searchRoleUserCondition.keyword"
                style="margin-top: 10px"
                :disabled="isDisable"
                placeholder="请输入关键词搜索..."
                enter-button
                @search="onSearchRoleUser"
        />
        <a-button type="primary" style="margin-top: 10px" :disabled="isDisable" @click="openAssociateUserModal">关联用户
        </a-button>
        <a-table :dataSource="roleUserList"
                 style="margin-top: 10px"
                 :columns="roleUserColumns"
                 :pagination="false"
                 size="small"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'status'">
                    {{text == 0 ? "在职" : (text == 1 ? "辞职" : (text == 2 ? "辞退" : "停职"))}}
                </template>
                <a-space v-if="column.key == 'action'">
                    <a-popconfirm
                            title="是否确认取消关联?"
                            :disabled="isDisable"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okCancel(record.id)"
                    >
                        <a-button type="danger" :disabled="isDisable">解除关联</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
    </a-drawer>
    <a-drawer
            v-model:visible="authorizationVisible"
            class="custom-class"
            width="600"
            title="角色权限配置"
            placement="right"
    >
        <a-alert :message="'《' + rolePermissionData.roleName + '》所拥有的权限'" type="info" show-icon>
            <template #icon>
                <smile-outlined/>
            </template>
        </a-alert>
        <a-tree
                checkable
                :selectable="false"
                :checkStrictly="true"
                :defaultExpandAll="true"
                v-model:checkedKeys="rolePermissionData.rolePermissionList"
                :tree-data="permissionList"
                :field-names="{title:'name',key:'id'}"
                @check="onChecked"
        >
        </a-tree>
        <template #footer>
            <a-space>
                <a-button type="default" @click="authorizationVisible = false">取消</a-button>
                <a-button type="primary" @click="okAuthorization">确认授权</a-button>
            </a-space>
        </template>
    </a-drawer>
    <a-modal v-model:visible="associateModalVisible" title="用户列表" @ok="okAssociateUser">
        <a-input-search
                v-model:value="notAssociateUserCondition.keyword"
                style="margin-top: 10px"
                placeholder="请输入关键词搜索..."
                enter-button
                @search="onSearchNotAssociateUser"
        />
        <a-table :dataSource="notAssociateUserList"
                 style="margin-top: 10px"
                 :columns="notAssociateUserColumns"
                 :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                 row-key="id"
                 :pagination="false"
                 size="small"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'status'">
                    {{text == 0 ? "在职" : (text == 1 ? "辞职" : (text == 2 ? "辞退" : "停职"))}}
                </template>
            </template>
        </a-table>
    </a-modal>
</template>

<script>
    import {ref, onMounted, watch, computed} from 'vue'
    import axios from 'axios'
    import {Form, message} from 'ant-design-vue';
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import {SmileOutlined} from '@ant-design/icons-vue'
    import {arrayToTree, isEmpty} from "@/utils/Tool";
    import store from '@/store'

    export default {
        name: "Role",
        components: {
            SmileOutlined
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                    align: 'center',
                },
                {
                    title: '角色名称',
                    dataIndex: 'name',
                    key: 'name',
                    align: 'center',
                },
                {
                    title: '基本工资',
                    dataIndex: 'baseSalary',
                    key: 'baseSalary',
                    align: 'center',
                },
                {
                    title: '所属部门',
                    dataIndex: 'departmentName',
                    key: 'departmentName',
                    align: 'center'
                },
                {
                    title: '角色描述',
                    dataIndex: 'remark',
                    key: 'remark',
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                }
            ]
            const roleUserColumns = [
                {
                    title: '用户账号',
                    dataIndex: 'userCode',
                    key: 'userCode',
                    align: 'center',
                },
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                    align: 'center',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    align: 'center',
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: '200px'
                }
            ]
            const notAssociateUserColumns = [
                {
                    title: '用户账号',
                    dataIndex: 'userCode',
                    key: 'userCode',
                    align: 'center',
                },
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                    align: 'center',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    align: 'center',
                },
            ]
            const loginUser = ref({})
            const locale = zhCN
            const role = ref({
                name: '',
                departmentId: undefined,
                baseSalary: undefined,
            })
            const searchRoleUserCondition = ref({})
            const notAssociateUserCondition = ref({})
            const roleList = ref()
            const roleUserList = ref([])
            const rolePermissionData = ref({
                roleId: null,
                roleName: null,
                rolePermissionList: []
            })

            const required = computed(() => {
                return role.value.isDepartmentRole == 1
            })

            watch(() => role.value.isDepartmentRole, () => {
                // console.log("执行查看")
                // resetFields()
                validateField('departmentId', role.value.departmentId, [{
                    required: required.value,
                    message: '请选择部门',
                    trigger: ['change']
                }])
                rulesRef.departmentId = [{
                    required: required.value,
                    message: '请选择部门',
                    trigger: ['change']
                }]
            })

            const useForm = Form.useForm
            const {validate, validateInfos, resetFields, validateField, rulesRef,} = useForm(role, {
                name: [{required: true, message: '请输入角色名', trigger: ['change']}],
                departmentId: [{
                    required: required.value,
                    message: '请选择部门',
                    trigger: ['change']
                }],
                baseSalary: [{required: true, message: '请输入基本工资', trigger: ['change']}],
            })

            const permissionList = ref([])
            const departmentList = ref([])
            const notAssociateUserList = ref([])
            const selectedRowKeys = ref([])
            const searchData = ref({})
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
            const visible = ref(false);
            const roleUserVisible = ref(false);
            const associateModalVisible = ref(false);
            const authorizationVisible = ref(false);
            const isDisable = ref(false)


            const saveOrUpdate = () => {
                validate().then(() => {
                    console.log("通过校验")
                    axios.post('/role/saveOrUpdate', role.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.code == 200) {
                            visible.value = false
                            message.success("操作成功")
                            load()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })

            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/role/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const openModal = (obj) => {
                console.log("模态框参数：", obj)
                role.value = JSON.parse(JSON.stringify(obj))
                // console.log("模态框参数aaaa：", role.value)
                if (isEmpty(role.value)) {
                    // console.log("aaaaa")
                    resetFields()
                }
                if (role.value.id == null) {
                    // console.log("bbbbb")
                    role.value.isDepartmentRole = 0
                }

                // console.log("模态框参数bbbb：", role.value)

                visible.value = true;
            }

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/role/queryPageByCondition', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        keyWord: searchData.value.keyWord,
                        departmentId: searchData.value.departmentId
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    roleList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const reset = () => {
                searchData.value = {}
                load()
            }

            const openRoleUserDraw = (id, isLeader) => {
                console.log("角色Id", id)
                console.log("是否领导角色：", isLeader)
                isDisable.value = isLeader == 1
                searchRoleUserCondition.value.roleId = id
                onSearchRoleUser()
                roleUserVisible.value = true
            }
            const onSearchRoleUser = () => {
                axios.get('user/queryByRoleIdAndKeyword', {
                    params: {
                        roleId: searchRoleUserCondition.value.roleId,
                        keyword: searchRoleUserCondition.value.keyword
                    }
                }).then(rs => {
                    roleUserList.value = rs.data
                })
            }

            const openAssociateUserModal = () => {
                notAssociateUserCondition.value.roleId = searchRoleUserCondition.value.roleId
                notAssociateUserCondition.value.keyword = null
                onSearchNotAssociateUser()
                associateModalVisible.value = true
            }

            const onSearchNotAssociateUser = () => {
                selectedRowKeys.value = []
                axios.get('user/queryByKeywordExcludeRole/', {
                    params: {
                        keyword: notAssociateUserCondition.value.keyword
                    }
                }).then(rs => {
                    notAssociateUserList.value = rs.data
                })
            }

            const onSelectChange = (keys) => {
                console.log("选择的ids", keys)
                selectedRowKeys.value = keys
            }

            const okAssociateUser = () => {
                axios.post('user/associate', {
                    roleId: notAssociateUserCondition.value.roleId,
                    userIds: selectedRowKeys.value
                }).then(rs => {
                    if (rs.code == 200) {
                        message.success("关联用户成功")
                        associateModalVisible.value = false
                        onSearchRoleUser()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const okCancel = (userId) => {
                axios.get('user/cancelAssociate/' + userId).then(rs => {
                    if (rs.code == 200) {
                        message.success("取消关联成功")
                        onSearchRoleUser()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const openAuthorization = (obj) => {
                rolePermissionData.value.roleId = obj.id
                rolePermissionData.value.roleName = obj.name
                axios.get('permission/queryByRoleId/' + obj.id).then(rs => {
                    rolePermissionData.value.rolePermissionList.checked = rs.data.map(item => item.id)
                    rolePermissionData.value.rolePermissionList.halfChecked = []
                    authorizationVisible.value = true
                    console.log("当前" + obj.name + "角色的权限：", rolePermissionData.value.rolePermissionList)
                })
            }

            const okAuthorization = () => {
                console.log("选中的权限集合：", rolePermissionData.value.rolePermissionList)
                axios.post('role-permission/authorizationByRoleId', {
                    roleId: rolePermissionData.value.roleId,
                    permissionList: rolePermissionData.value.rolePermissionList.checked
                }).then(rs => {
                    if (rs.code == 200) {
                        message.success("授权成功")
                        authorizationVisible.value = false
                        if (rolePermissionData.value.roleId == loginUser.value.roleId) {
                            location.reload()
                        }
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const onChecked = (checkedKeys, e) => {
                console.log("checkedKeys", checkedKeys)
                console.log("e", e)
                // if (e.node.dataRef.parentId != 0 &&
                //     checkedKeys.checked.indexOf(e.node.dataRef.parentId) == -1
                // && e.node.dataRef) {
                //     checkedKeys.checked.push(e.node.dataRef.parentId)
                // }
            }

            onMounted(() => {
                loginUser.value = store.state.user
                axios.get('department/queryAll').then(rs => {
                    departmentList.value = rs.data
                })
                axios.get('permission/queryAll').then(rs => {
                    let permissionListTemp = rs.data
                    permissionListTemp.forEach(item => {
                        if (item.isPublic == 1) {
                            item.disableCheckbox = true
                            item.disabled = true
                        }
                    })
                    permissionList.value = arrayToTree(permissionListTemp, 0)
                })
                load()
            })
            return {
                columns,
                role,
                roleList,
                departmentList,
                pagination,
                pageSizeOptions,
                onChange,
                load,
                locale,
                searchData,
                reset,
                visible,
                openModal,
                saveOrUpdate,
                okDelete,
                roleUserVisible,
                openRoleUserDraw,
                searchRoleUserCondition,
                onSearchRoleUser,
                roleUserList,
                roleUserColumns,
                associateModalVisible,
                okAssociateUser,
                notAssociateUserCondition,
                notAssociateUserColumns,
                onSearchNotAssociateUser,
                notAssociateUserList,
                openAssociateUserModal,
                selectedRowKeys,
                onSelectChange,
                okCancel,
                isDisable,
                openAuthorization,
                rolePermissionData,
                authorizationVisible,
                okAuthorization,
                permissionList,
                onChecked,
                validateInfos,
                resetFields,
                required
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>